package ltd.hxya.novel.gateway.filter;

import com.alibaba.fastjson.JSON;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.common.bean.ResultEnum;
import ltd.hxya.novel.common.constant.SecurityConstant;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        List<String> isAuth = request.getHeaders().get(SecurityConstant.IS_AUTHENTICATION);
        if (!CollectionUtils.isEmpty(isAuth)){
            //用户并非使用正规操作访问，返回错误提示
            ServerHttpResponse response = exchange.getResponse();
            Result<Void> result = Result.fail(ResultEnum.OPERATION_EXCEPTION.getCode(), ResultEnum.OPERATION_EXCEPTION.getMsg());
            DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8));
            return response.writeWith((Mono.just(buffer)));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
